package logic

import (
	"context"
	"encoding/json"
	"good_srv/cache"
	"good_srv/good"
	"good_srv/internal/svc"
	"good_srv/models"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodShowLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodShowLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodShowLogic {
	return &GoodShowLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodShowLogic) GoodShow(in *good.GoodShowRequest) (*good.GoodShowResponse, error) {
	// todo: add your logic here and delete this line
	var goods models.Good
	models.DB.Where("id=?", in.Id).Find(&goods)
	result, _ := cache.Rdb.Get(l.ctx, "good_show").Result()
	if result != "" {
		json.Unmarshal([]byte(result), &goods)
	} else {
		marshal, _ := json.Marshal(&goods)
		cache.Rdb.Set(l.ctx, "good_show", marshal, time.Minute*5)
	}
	return &good.GoodShowResponse{
		Title:  goods.Title,
		Price:  float32(goods.Price),
		Stock:  goods.Stock,
		Image:  goods.Image,
		Status: goods.Status,
	}, nil
}
